package com.mask.im.server.netty.action.handler;

import com.alibaba.fastjson.JSON;
import com.mask.im.server.netty.IMChannelCtxMap;
import com.mask.im.server.netty.enums.IMActionEnum;
import com.mask.im.server.netty.model.IMReceiveMessage;
import com.mask.im.server.netty.model.IMSendMessage;
import com.mask.im.server.service.ServiceIdManager;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.AttributeKey;
import lombok.extern.log4j.Log4j2;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author jian
 * @description 注册用户到服务中
 * @date 2025/10/11 14:31
 */
@Log4j2
@Component
public class IMRegisterActionHandler extends IMAbstractChatHandler {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private ServiceIdManager serviceIdManager;

    @Override
    public IMActionEnum getAction() {
        return IMActionEnum.REGISTER;
    }

    @Override
    public void handle(IMReceiveMessage imReceiveMessage, Channel channel) {
        // todo 实现注册后的一些功能,例如初始化心跳次数,初始化用户id绑定等等
        // 获取用户id
        // 初始化心跳次数
        AttributeKey<Long> userIdAttributeKey = AttributeKey.valueOf("USER_ID");
        Long userId = channel.attr(userIdAttributeKey).get();
        log.info("netty注册初始化心跳用户id:{}", userId);
        // 绑定用户数据
        IMChannelCtxMap.setUserIdAndIdBindChannel(userId.toString(), channel);
        // 初始化心跳次数
        AttributeKey<Long> heartBeatCount = AttributeKey.valueOf("HEART_BEAT_COUNT");
        //存放次数
        channel.attr(heartBeatCount).set(0L);
        log.info("netty注册初始化心跳用户:{},次数:{}", userId, 0);
        //用户注册到redis节点
        redisTemplate.opsForValue().set("im:user:node:" + userId + ":default", serviceIdManager.getNodeId(), 800, TimeUnit.SECONDS);
        // 响应ws
        IMSendMessage sendInfo = new IMSendMessage();
        sendInfo.setCmd(IMActionEnum.REGISTER.getAction());
        channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(sendInfo)));
    }
}
